package dao.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public abstract class Mybatis_create<E> {
       private String resource = "mybatis-config.xml";
       private InputStream inputStream;
    {
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String toString() {
        return "Mybatis_create{" +
                "resource='" + resource + '\'' +
                ", inputStream=" + inputStream +
                ", sqlSessionFactory=" + sqlSessionFactory +
                ", session=" + session +
                '}';
    }

    SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
    // 不在字段初始化时永久持有一个会话；提供激活获取方法，避免“Executor was closed”
    protected SqlSession session = sqlSessionFactory.openSession();

    // 获取一个确保可用的 SqlSession
    protected SqlSession getActiveSession() {
        if (session == null) {
            session = sqlSessionFactory.openSession();
        }
        return session;
    }
    protected abstract E getMapperClass();
    public   void  commitsession(){
        session.commit();
    }
    // 兼容新旧命名：提供简洁的别名方法
    public   void  commit(){
        session.commit();
    }
    public   void  closesession(){
        if (session != null) {
            try { session.close(); } finally { session = sqlSessionFactory.openSession(); }
        } else {
            session = sqlSessionFactory.openSession();
        }
    }
    public   void  closeSession(){
        if (session != null) {
            try { session.close(); } finally { session = sqlSessionFactory.openSession(); }
        } else {
            session = sqlSessionFactory.openSession();
        }
    }
    public String getResource() {
        return resource;
    }

    public void setResource(String resource) {
        this.resource = resource;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    public SqlSession getSession() {
        return session;
    }

    public void setSession(SqlSession session) {
        this.session = session;
    }
}
